# -*- coding: utf-8 -*-
"""
文件上传路由
专门处理文件上传相关的API接口
"""

from fastapi import APIRouter, Depends, HTTPException, status, UploadFile, File
from src.schemas.detection import (
    UploadImageResponse,
    SaveImageRequest,
    SaveImageResponse,
    ImagePreprocessingRequest,
    ImagePreprocessingResponse,
    ImagePreprocessingApiResponse
)
from src.schemas import SuccessResponse
from src.services.detection_service import DetectionService
from src.services.file_service import FileService
from src.utils.auth import get_current_user
from src.models import User
from src.utils.logger import app_logger as logger

router = APIRouter(prefix="/upload")


@router.post(
    "/oss",
    response_model=SuccessResponse[UploadImageResponse],
    summary="上传文件到OSS",
    description="仅上传文件到阿里云OSS，返回文件URL和存储路径，不保存数据库记录"
)
async def upload_to_oss(
    file: UploadFile = File(..., description="要上传的文件"),
    current_user: User = Depends(get_current_user)
):
    """上传文件到OSS"""
    try:
        # 创建文件服务实例
        file_service = FileService()
        
        # 验证文件
        file_service.validate_image_file(file)
        
        # 上传到OSS
        result = await file_service.upload_to_oss(
            current_user.id,
            file
        )
        return SuccessResponse(
            data=result,
            message="文件上传到OSS成功"
        )
    except Exception as e:
        logger.error(f"文件上传到OSS失败: {str(e)}")
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=str(e)
        )


@router.post(
    "/save-record",
    response_model=SuccessResponse[SaveImageResponse],
    summary="保存文件信息到数据库",
    description="将OSS文件URL和路径保存到数据库，创建文件记录"
)
async def save_file_record(
    request: SaveImageRequest,
    current_user: User = Depends(get_current_user)
):
    """保存文件信息到数据库"""
    try:
        result = await DetectionService.save_image_record(
            current_user.id,
            request.image_url,
            request.oss_path
        )
        return SuccessResponse(
            data=result,
            message="文件信息保存成功"
        )
    except Exception as e:
        logger.error(f"保存文件信息失败: {str(e)}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"保存文件信息失败: {str(e)}"
        )


@router.post(
    "/image",
    response_model=SuccessResponse[UploadImageResponse],
    summary="上传图片（完整流程）",
    description="上传图片到阿里云OSS并保存到数据库，一步完成完整上传流程"
)
async def upload_image_complete(
    file: UploadFile = File(..., description="图片文件"),
    current_user: User = Depends(get_current_user)
):
    """上传图片（完整流程）"""
    try:
        # 创建文件服务实例
        file_service = FileService()
        
        # 验证文件
        file_service.validate_image_file(file)
        
        # 完整上传流程（包含数据库保存）
        detection_service = DetectionService()
        result = await detection_service.upload_image(
            current_user.id,
            file
        )
        return SuccessResponse(
            data=result,
            message="图片上传成功"
        )
    except Exception as e:
        logger.error(f"图片上传失败: {str(e)}")
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=str(e)
        )


@router.post(
    "/batch",
    response_model=SuccessResponse[list[UploadImageResponse]],
    summary="批量上传文件",
    description="批量上传多个文件到OSS，支持同时上传多个文件"
)
async def upload_batch_files(
    files: list[UploadFile] = File(..., description="要上传的文件列表"),
    current_user: User = Depends(get_current_user)
):
    """批量上传文件"""
    try:
        # 验证文件数量
        if len(files) > 10:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="单次最多上传10个文件"
            )
        
        # 创建文件服务实例
        file_service = FileService()
        
        results = []
        for file in files:
            try:
                # 验证文件
                file_service.validate_image_file(file)
                
                # 上传到OSS
                result = await file_service.upload_to_oss(
                    current_user.id,
                    file
                )
                results.append(result)
            except Exception as e:
                logger.error(f"文件 {file.filename} 上传失败: {str(e)}")
                # 继续处理其他文件，不中断整个批量上传
                continue
        
        if not results:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="所有文件上传失败"
            )
        
        return SuccessResponse(
            data=results,
            message=f"批量上传完成，成功上传 {len(results)} 个文件"
        )
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"批量上传失败: {str(e)}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=str(e)
        )


@router.post(
    "/image-preprocessing",
    response_model=ImagePreprocessingApiResponse,
    summary="图片预处理检查",
    description="调用AI检查上传的图片是否可用（确认照片是否是人头部照片）"
)
async def image_preprocessing(
    request: ImagePreprocessingRequest,
    current_user: User = Depends(get_current_user)
):
    """图片预处理：检查图片是否为人头部照片"""
    try:
        # 验证图片数量
        if len(request.image_urls) != 3:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="必须提供3张图片的URL"
            )
        
        # 创建检测服务实例
        detection_service = DetectionService()
        
        # 调用AI检查图片有效性
        is_all_valid = await detection_service.preprocess_images(request.image_urls)
        
        return ImagePreprocessingApiResponse(
            data=ImagePreprocessingResponse(is_all_valid=is_all_valid),
            message="图片预处理检查完成"
        )
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"图片预处理失败: {str(e)}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"图片预处理失败: {str(e)}"
        )